<?php

namespace App\Console\Commands;

use App\Models\Call;
use App\Service\SwooleFreeswitch;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SwooleCallcenterListen extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole:callcenter:listen';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '群呼监听';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        \Swoole\Coroutine\run(function () {
            $fs = new SwooleFreeswitch();
            if (!$fs->connect()) {
                return false;
            }

            $record_url = config('freeswitch.record_url');
            $fs_dir = '/usr/local/freeswitch';

            $fs->events("CUSTOM fifo::info");

            while (true) {
                $received_parameters = $fs->recvEvent();
                if (!empty($received_parameters)) {
                    $json = $fs->serialize($received_parameters);
                    $action = Arr::get($json, 'FIFO-Action', null);
                    $uuid = Arr::get($json, 'Unique-ID', null);
                    $date = urldecode(Arr::get($json, 'Event-Date-Local', null));
                    $call = Call::query()->where('aleg_uuid',$uuid)->first();
                    switch ($action) {
                        // 进入队列
                        case 'push':
                            $call->update([
                                'status' => 3,
                                'datetime_entry_queue' => $date,
                            ]);
                            break;
                        // 队列等待中挂断
                        case 'abort':
                            $call->update([
                                'datetime_end' => $date,
                            ]);
                            break;
                        // 接听
                        case 'bridge-caller-start':
                            $username = Arr::get($json, 'Caller-Caller-ID-Number', null);
                            $user = DB::table('user')
                                ->join('sip','user.sip_id','sip.id')
                                ->where('sip.username',$username)
                                ->select(['user.id as user_id','user.nickname as user_nickname','sip.id as sip_id','sip.username as sip_username'])
                                ->first();
                            //录音
                            $filepath = $fs_dir . '/recordings/' . date('Y/m/d/');
                            $file = $filepath . 'callcenter_' . md5($uuid . time() . uniqid()) . '.wav';
                            $fs->bgapi("uuid_record " . $file . " start " . $file . " 1800");

                            $call->update([
                                'datetime_sip_answer' => date('Y-m-d H:i:s'),
                                'record_file' => str_replace($fs_dir,$record_url,$file),
                                'sip_username' => $username,
                                'sip_id' => $user->sip_id??0,
                                'user_id' => $user->user_id??0,
                                'user_nickname' => $user->user_nickname??null,
                            ]);
                            //弹出客户号码添加客户
                            if ($user != null){
                                push_message(
                                    'callcenter',
                                    [
                                        'title'=>'群呼-备注客户',
                                        'content' => $call->phone,
                                    ],
                                    [$user->id]
                                );
                            }
                            break;
                        // 挂断
                        case 'bridge-caller-stop':
                            $billsec = Arr::get($json, 'FIFO-Caller-Talk-Time-s', 0);
                            $call->update([
                                'datetime_end' => $date,
                                'billsec' => $billsec,
                            ]);
                            break;
                        default:
                            break;
                    }
                }
            }
            $fs->disconnect();
        });

    }
}
